package udpEcho;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket=null;
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        socket=new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner sc=new Scanner(System.in);
        while(true){
            System.out.println("请输入请求：");
            if(!sc.hasNextLine()){
                break;
            }
            String request=sc.next();
            //1.发送请求给服务器，要构造DatagramPacket对象
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIP), serverPort);
            //2.发送数据报
            socket.send(requestPacket);
            //3.接受服务器响应
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4.对读取的信息进行解析
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
